﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using CoTime.Model;
using CoTime.View.UserControls;
using CoTime.ViewModel;

namespace CoTime.View
{
    public partial class UCTdt : UserControl
    {
        readonly MainWindowViewModel _viewModel;

        #region [ 任务属性 ]

        public UCCanvas SelectedTask { get; set; }
        public String SelectedTaskId {
            get 
            {
                if (SelectedTask != null)
                {
                    return this.SelectedTask.Name.Replace(Consts.Task, "");
                }
                return String.Empty;
            }
        }

        public UCCanvas WorkingTask { get; set; }
        public String WorkingTaskId
        {
            get
            {
                if (WorkingTask != null)
                {
                    return this.WorkingTask.Name.Replace(Consts.Task, "");
                }
                return String.Empty;
            }
        }
        private UCCanvas GetIconOperationPointedTask(Boolean auto)
        {
            if (auto && this.WorkingTask != null)
            {
                return this.WorkingTask;
            }
            else
            {
                return this.SelectedTask;
            }
        }
        private String GetIconOperationPointedTaskId(Boolean auto)
        {
            if (auto && this.WorkingTask != null)
            {
                return this.WorkingTaskId;
            }
            else
            {
                return this.SelectedTaskId;
            }
        }

        #endregion

        #region [ Constructors ]

        public UCTdt()
        {
            InitializeComponent();
        }

        public UCTdt(MainWindowViewModel viewModel) : this()
        {
            this._viewModel = viewModel;
            InitUI();
            BindUIData(DateTime.Today.Date);
        }

        #endregion

        #region [ Init ]

        void InitUI()
        {
            for (Int32 i = 0; i < 21; i++)
            {
                var row = new UCCanvas(i);

                ((UCTextBox) row.Children[1]).GotFocus += new RoutedEventHandler(textBox_GotFocus);
                row.Width = this.Width;
                if (i < 14)
                {
                    stackPanel1.Children.Add(row);
                }
                else if (i > 13 && i < 21)
                {
                    stackPanel2.Children.Add(row);
                }
            }
            SmartBackgroud();
        }

        void BindUIData(DateTime date)
        {
            Boolean isToday = date.Date.Equals(DateTime.Today.Date);

            List<Task> tasks = _viewModel.GetTasks(date);

            if (tasks != null)
            {
                var rows = stackPanel1.FindAll<UCCanvas>();
                rows.AddRange(stackPanel2.FindAll<UCCanvas>());
                Int32 i = 0;
                for (; i < 14; i++)
                {
                    rows[i].BindTask(tasks.GetTaskById(i));
                }
                for (; i < 21; i++)
                {
                    rows[i].BindTask(tasks.GetTaskById(i));
                }

                if (isToday)
                {
                    this.SelectedTask = rows[0];
                    this.SelectedTask.First<Image>().Visibility = System.Windows.Visibility.Visible;
                    this.SelectedTask.First<UCTextBox>().Focus();
                }
            }
            ((MainWindow) Application.Current.MainWindow).AdjustButtonsStatus(isToday);
        }

        void textBox_GotFocus(object sender, RoutedEventArgs e)
        {
            if (this.SelectedTask != null)
            {
                if ((this.SelectedTask.First<Image>().Tag as String) != "done")
                {
                    this.SelectedTask.First<Image>().Visibility = Visibility.Hidden;
                }
            }
            this.SelectedTask = ((UCTextBox) sender).Parent as UCCanvas;
            this.SelectedTask.First<Image>().Visibility = Visibility.Visible;
            //TODO:fix this!
            //FreezePomoBtns();
        }

        #endregion

        #region [ Smart UI ]

        void SmartBackgroud()
        {
            String[] files = Directory.GetFiles(Config.AppPath + "Images/", "bg*");
            if (files.Length <= 0) return;
            var random = new Random();
            var i = random.Next(0, files.Length);
            var imageBrush = new ImageBrush();
            var bitmap = new BitmapImage(new Uri(files[i]));
            {
                imageBrush.ImageSource = bitmap;
                imageBrush.Stretch = Stretch.None;
                imageBrush.AlignmentX = AlignmentX.Left;
                imageBrush.AlignmentY = AlignmentY.Top;
                if (bitmap.Width < 150)
                {
                    imageBrush.TileMode = TileMode.Tile;
                    imageBrush.ViewportUnits = BrushMappingMode.Absolute;
                    imageBrush.Viewport = new Rect(0, 0, bitmap.Width, bitmap.Height);
                }
                this.Background = imageBrush;
            }
        }

        #endregion

        #region [ UI To Model Mappers ]

        public List<Task> TasksMapper()
        {
            var tasks = new List<Task>();

            stackPanel1.Dispatcher.Invoke(new Action(() => stackPanel1.FindAll<UCCanvas>().ForEach(canvas => tasks.Add(canvas.ToTask()))));
            stackPanel2.Dispatcher.Invoke(new Action(() => stackPanel2.FindAll<UCCanvas>().ForEach(canvas => tasks.Add(canvas.ToTask()))));

            return tasks;
        }

        #endregion

        #region [ Api ]

        public void AddTask(Task task)
        {
            UCTextBox textBox = null;
            for (Int32 i = 0; i < this.stackPanel1.Children.Count; i++)
            {
                var canvas = this.stackPanel1.Children[i] as UCCanvas;
                if (canvas != null)
                {
                    var txtBox = canvas.First<UCTextBox>();
                    if (txtBox != null && String.IsNullOrWhiteSpace(txtBox.Text))
                    {
                        textBox = txtBox;
                        ((Task) canvas.Tag).UUID = task.UUID;
                        break;
                    }
                }
            }
            if (textBox != null)
            {
                textBox.Text = task.Title;
            }
        }

        public Boolean Contains(Task task)
        {
            return _viewModel.Tasks.Exists(t => t.UUID == task.UUID);
        }

        public void StartPomoOnWorkingTask()
        {
            this.WorkingTask = this.SelectedTask;
            this.WorkingTask.Background = Brushes.SkyBlue;
        }

        public void AbanPomoOnWorkingTask()
        {
            this.WorkingTask.AddAban();
            this.WorkingTask.Background = null;
            this.WorkingTask = null;
        }

        public void FiniPomoOnWorkingTask()
        {
            this.WorkingTask.AddPomo();
            this.WorkingTask.Background = null;
            this.WorkingTask = null;
        }

        #endregion

        #region [ Browse "Buttons" ]

        private void ToDoTodayMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (!ToDoToday.Content.Equals(Consts.ToDoToday))
            {
                ToDoToday.Content = Consts.ToDoToday;
                Prev.Visibility = Visibility.Visible;
                Next.Visibility = Visibility.Hidden;
                BindUIData(DateTime.Today);
                e.Handled = true;
            }
        }

        private void PrevMouseDown(object sender, MouseButtonEventArgs e)
        {
            DateTime dt;
            if (ToDoToday.Content.Equals(Consts.ToDoToday))
            {
                ((MainWindow)Application.Current.MainWindow).Save();
                dt = DateTime.Today.AddDays(-1);
                ToDoToday.Content = ToDoToday.Content.ToString().Replace("TO DO TODAY", dt.ToString("yyyy-MM-dd"));
            }
            else
            {
                dt = DateTime.Parse(ToDoToday.Content.ToString().Trim('-', ' '));
                ToDoToday.Content = ToDoToday.Content.ToString().Replace(dt.ToString("yyyy-MM-dd"), dt.AddDays(-1).ToString("yyyy-MM-dd"));
                dt = dt.AddDays(-1);
            }
            Next.Visibility = Visibility.Visible;
            BindUIData(dt);
        }

        private void NextMouseDown(object sender, MouseButtonEventArgs e)
        {
            DateTime dt;
            if (ToDoToday.Content.ToString().Contains(DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd")))
            {
                dt = DateTime.Today;
                ToDoToday.Content = ToDoToday.Content.ToString().Replace(dt.AddDays(-1).ToString("yyyy-MM-dd"), "TO DO TODAY");
                Next.Visibility = Visibility.Hidden;
            }
            else
            {
                dt = DateTime.Parse(ToDoToday.Content.ToString().Trim('-', ' '));
                ToDoToday.Content = ToDoToday.Content.ToString().Replace(dt.ToString("yyyy-MM-dd"), dt.AddDays(1).ToString("yyyy-MM-dd"));
                dt = dt.AddDays(1);
            }
            BindUIData(dt);
        }

        private void BrowseNavigatorMouseEnter(object sender, MouseEventArgs e)
        {
            Prev.Visibility = Next.Visibility = Visibility.Visible;
            if (ToDoToday.Content.ToString().Equals(Consts.ToDoToday))
            {
                Next.Visibility = Visibility.Hidden;
            }
        }

        private void BrowseNavigatorMouseLeave(object sender, MouseEventArgs e)
        {
            Prev.Visibility = Next.Visibility = Visibility.Hidden;
        }

        #endregion
    }
}
